package br.ufu.facom.calendar;

import java.util.Calendar;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements
		TimePickerDialog.OnTimeSetListener {

	private DateTimeHandler dt;
	private String title;
	private TimePickerDialog tm;

	public void setDateTimeHandler(DateTimeHandler dt) {
		this.dt = dt;
		if (this.tm != null) {
			Calendar c = this.dt.getCalendar();
			tm.updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
		}
	}

	public void setTitle(String title) {
		this.title = title;
		if (this.tm != null)
			this.tm.setTitle(title);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current time as the default values for the picker
		final Calendar c;
		if (this.dt != null)
			c = this.dt.getCalendar();
		else
			c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		// Create a new instance of TimePickerDialog and return it
		this.tm = new TimePickerDialog(getActivity(), this, hour, minute,
				DateFormat.is24HourFormat(getActivity()));
		if (this.title != null)
			this.tm.setTitle(this.title);
		return this.tm;
	}

	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		if (this.dt != null)
			this.dt.setTime(view);
	}
}
